package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.equipment.entity.EquipmentCheckTask;
import com.mxpio.erp.common.equipment.entity.EquipmentCheckTaskDetail;
import com.mxpio.erp.common.equipment.entity.EquipmentCheckTaskTransfer;
import com.mxpio.erp.common.equipment.service.EquipmentCheckTaskDetailService;
import com.mxpio.erp.common.equipment.service.EquipmentCheckTaskService;
import com.mxpio.erp.common.equipment.service.EquipmentCheckTaskTransferService;
import com.mxpio.erp.common.equipment.vo.EquipmentCheckTaskPage;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 点检任务
 * @Author: jeecg-boot
 * @Date:   2021-09-23
 * @Version: V1.0
 */
@Tag(name = "EquipmentCheckTaskController", description = "点检任务")
@RestController
@RequestMapping("/erp/equipment/spotcheck/tpmCheckTask")
@Slf4j
public class EquipmentCheckTaskController {
	@Autowired
	private EquipmentCheckTaskService equipmentCheckTaskService;
	@Autowired
	private EquipmentCheckTaskDetailService equipmentCheckTaskDetailService;
	@Autowired
	private EquipmentCheckTaskTransferService equipmentCheckTaskTransferService;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param criteria
     * @return
     */
    @GetMapping(value = "/page")
    @Operation(summary = "点检任务-分页列表查询", description = "点检计划明细选项-分页列表查询", method = "GET")
    public Result<?> queryPageList(@RequestParam(name = "flag", defaultValue = "task") String flag,
                                   @RequestParam(name = "planStart", required = false) String planStart,
                                   @RequestParam(name = "planEnd", required = false) String planEnd,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    Criteria criteria) {
            Pageable page = PageRequest.of(pageNo-1, pageSize);
            Page<EquipmentCheckTask> pageList = equipmentCheckTaskService.listPage(EquipmentCheckTask.class,page, criteria);
            return Result.OK(pageList);
    }

     /**
     * 添加
     *
     * @param equipmentCheckTaskPage
     * @return
     */
    @PostMapping(value = "/add")
    @Operation(summary = "点检任务-添加", description = "点检任务-添加", method = "POST")
    public Result<?> add(@RequestBody EquipmentCheckTaskPage equipmentCheckTaskPage) throws MBootException {
        EquipmentCheckTask equipmentCheckTask = new EquipmentCheckTask();
        BeanUtils.copyProperties(equipmentCheckTaskPage, equipmentCheckTask);
        equipmentCheckTaskService.saveMain(equipmentCheckTask, equipmentCheckTaskPage.getEquipmentCheckTaskDetailList(), equipmentCheckTaskPage.getEquipmentCheckTaskTransferList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param equipmentCheckTask
     * @return
     */
    @PutMapping(value = "/edit")
    @Operation(summary = "点检任务-编辑", description = "点检任务-编辑", method = "PUT")
    public Result<?> edit(@RequestBody EquipmentCheckTask equipmentCheckTask) throws MBootException {
//        equipmentCheckTaskService.updateMain(equipmentCheckTask, null,null);
        equipmentCheckTaskService.update(equipmentCheckTask);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    @Operation(summary = "点检任务-通过id删除", description = "点检任务-通过id删除", method = "DELETE")
    public Result<?> delete(@PathVariable(name = "id", required = true) String id) {
        equipmentCheckTaskService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    @Operation(summary = "点检任务-批量删除", description = "点检任务-批量删除", method = "DELETE")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.equipmentCheckTaskService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    @Operation(summary = "点检任务-通过id查询", description = "点检任务-通过id查询", method = "GET")
    public Result<?> queryById(@PathVariable(name = "id", required = true) String id) {
        EquipmentCheckTask equipmentCheckTask = equipmentCheckTaskService.getById(EquipmentCheckTask.class,id);
        if (equipmentCheckTask == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(equipmentCheckTask);

	}

    /**
     * 通过id查询
     *
     * @return
     */
    @GetMapping(value = "/detail/page")
    @Operation(summary = "点检任务明细-通过主表ID查询", description = "点检任务明细-点检任务明细", method = "GET")
    public Result<?> queryEquipmentCheckTaskDetailListByMainId(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               Criteria criteria) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentCheckTaskDetail> pageList = equipmentCheckTaskDetailService.listPage(EquipmentCheckTaskDetail.class,page, criteria);
        return Result.OK(pageList);
    }

    @GetMapping("/detail/list")
    @Operation(summary = "点检任务明细", description = "点检任务明细列表（无分页）", method = "GET")
    public Result<?> queryEquipmentCheckTaskDetailList(@Parameter(description = "查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<EquipmentCheckTaskDetail> list = equipmentCheckTaskDetailService.list(EquipmentCheckTaskDetail.class, criteria);
        return Result.OK(list);
    }

    /**
     * 新增任務明細
     *
     * @return
     */
    @PostMapping(value = "/detail/add")
    @Operation(summary = "点检任务明細-添加", description = "点检任务明細-添加", method = "POST")
    public Result<?> addDetail(@RequestBody EquipmentCheckTaskDetail equipmentCheckTaskDetail) {
        equipmentCheckTaskDetailService.addDetail(equipmentCheckTaskDetail);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     * @param equipmentCheckTaskDetail
     * @return
     */
    @PutMapping(value = "/detail/edit")
    @Operation(summary = "点检任务明细-编辑", description = "点检任务明细-编辑", method = "PUT")
    public Result<?> editEquipmentCheckTaskDetail(@RequestBody EquipmentCheckTaskDetail equipmentCheckTaskDetail) {
        equipmentCheckTaskDetailService.update(equipmentCheckTaskDetail);
        return Result.OK("编辑成功!");
    }
    /**
     * 通过id查询
     *
     * @return
     */
    @GetMapping(value = "/transfer/page")
    @Operation(summary = "点检任务转单明细-通过主表ID查询", description = "点检任务转单明细-点检任务明细", method = "GET")
    public Result<?> queryEquipmentCheckTaskTransferListByMainId(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                 Criteria criteria) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentCheckTaskTransfer> pageList = equipmentCheckTaskTransferService.listPage(EquipmentCheckTaskTransfer.class,page, criteria);
        return Result.OK(pageList);
    }

//    /**
//     * 导出excel
//     *
//     * @param request
//     * @param equipmentCheckTask
//     */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, EquipmentCheckTask equipmentCheckTask) {
//        // Step.1 组装查询条件查询数据
//        QueryWrapper<EquipmentCheckTask> queryWrapper = QueryGenerator.initQueryWrapper(equipmentCheckTask, request.getParameterMap());
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//        //Step.2 获取导出数据
//        List<EquipmentCheckTask> queryList = equipmentCheckTaskService.list(queryWrapper);
//        // 过滤选中数据
//        String selections = request.getParameter("selections");
//        List<EquipmentCheckTask> equipmentCheckTaskList = new ArrayList<EquipmentCheckTask>();
//        if (oConvertUtils.isEmpty(selections)) {
//            equipmentCheckTaskList = queryList;
//        } else {
//            List<String> selectionList = Arrays.asList(selections.split(","));
//            equipmentCheckTaskList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
//        }
//
//      // Step.3 组装pageList
//      List<EquipmentCheckTaskExportPage> pageList = new ArrayList<>();
//      for (EquipmentCheckTask main : equipmentCheckTaskList) {
//		  EquipmentCheckTaskExportPage vo = new EquipmentCheckTaskExportPage();
//          BeanUtils.copyProperties(main, vo);
//		  //处理审核流程显示
//		  StringBuilder activitiHistory = new StringBuilder("");
//		  //查询processInstanceId
//		  List<ActReModelFormData> actReModelFormDataList = actReModelFormDataService.list(
//		  		(Wrapper)((QueryWrapper)(new QueryWrapper()).eq("table_id", "3edf72be6a2c4c12ad132d6fc15b6f59"))
//															.eq("data_id", main.getId()));
//		  if (actReModelFormDataList.size()>0){
//			  for (ActReModelFormData formData :actReModelFormDataList) {
//				  String processInstanceId = formData.getProcessInstanceId();
//				  //获取签核历史
//				  Result historic = activitiHistoryController.historicFlow(processInstanceId, "");
//				  if (historic != null && historic.getResult() != null) {
//					  List<JSONObject> list = (List<JSONObject>) historic.getResult();
//					  if (list.size() > 0) {
//						  //编辑签核list，组装签核历史字符串
//						  for (JSONObject object:list){
//							  Object assignee = object.get("assignee");
//							  Object endtime = object.get("endTime");
//							  if (endtime != null) {
//								  activitiHistory.append(assignee.toString() + "/" + endtime.toString() + "->");
//							  }else if (assignee != null && assignee != ""){
//								  activitiHistory.append(assignee.toString() + "->");
//							  }
//						  }
//						  if (activitiHistory.length() > 3){
//							  activitiHistory.delete(activitiHistory.length() - 2, activitiHistory.length());
//						  }
//						  activitiHistory.append(",");
//					  }
//			 	  }
//			  }
//			  if (activitiHistory.length() > 2){
//				  activitiHistory.delete(activitiHistory.length()-1,activitiHistory.length());
//			  }
//		  }
//		  vo.setActivitiHistory(activitiHistory.toString());
//		  //审核流程结束
//          List<EquipmentCheckTaskDetailExport> equipmentCheckTaskDetailList = equipmentCheckTaskDetailService.selectExportByMainId(main.getId());
//          vo.setEquipmentCheckTaskDetailExportList(equipmentCheckTaskDetailList);
//          pageList.add(vo);
//      }
//
//      // Step.4 AutoPoi 导出Excel
//      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//      mv.addObject(NormalExcelConstants.FILE_NAME, "点检任务列表");
//      mv.addObject(NormalExcelConstants.CLASS, EquipmentCheckTaskExportPage.class);
//      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("点检任务数据", "导出人:"+sysUser.getRealname(), "点检任务"));
//      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
//      return mv;
//    }
//
//     /**
//      * 点检任务-导出pdf
//      * @return
//      */
//     @SneakyThrows
//     @AutoLog(value = "点检任务-导出pdf")
//     @ApiOperation(value="点检任务-导出pdf", notes="点检任务-导出pdf")
//     @RequestMapping(value = "/exportPdf")
//     public ModelAndView exportPdf(HttpServletRequest request, EquipmentCheckTask equipmentCheckTask){
//         // Step.1 组装查询条件查询数据
//         QueryWrapper<EquipmentCheckTask> queryWrapper = QueryGenerator.initQueryWrapper(equipmentCheckTask, request.getParameterMap());
//         LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//         //Step.2 获取导出数据
//         List<EquipmentCheckTask> queryList = equipmentCheckTaskService.list(queryWrapper);
//         // 过滤选中数据
//         String selections = request.getParameter("selections");
//         List<EquipmentCheckTask> equipmentCheckTaskList = new ArrayList<EquipmentCheckTask>();
//         if(oConvertUtils.isEmpty(selections)) {
//             equipmentCheckTaskList = queryList;
//         }else {
//             List<String> selectionList = Arrays.asList(selections.split(","));
//             equipmentCheckTaskList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
//         }
//
//         // Step.3 组装pageList
//         List<EquipmentCheckTaskExportPage> pageList = new ArrayList<>();
//         for (EquipmentCheckTask main : equipmentCheckTaskList) {
//             EquipmentCheckTaskExportPage vo = new EquipmentCheckTaskExportPage();
//             BeanUtils.copyProperties(main, vo);
//             //处理审核流程显示
//             StringBuilder activitiHistory = new StringBuilder("");
//             //查询processInstanceId
//             List<ActReModelFormData> actReModelFormDataList = actReModelFormDataService.list(
//                     (Wrapper)((QueryWrapper)(new QueryWrapper()).eq("table_id", "3edf72be6a2c4c12ad132d6fc15b6f59"))
//                             .eq("data_id", main.getId()));
//             if (actReModelFormDataList.size()>0){
//                 for (ActReModelFormData formData :actReModelFormDataList) {
//                     String processInstanceId = formData.getProcessInstanceId();
//                     //获取签核历史
//                     Result historic = activitiHistoryController.historicFlow(processInstanceId, "");
//                     if (historic != null && historic.getResult() != null) {
//                         List<JSONObject> list = (List<JSONObject>) historic.getResult();
//                         if (list.size() > 0) {
//                             //编辑签核list，组装签核历史字符串
//                             for (JSONObject object:list){
//                                 Object assignee = object.get("assignee");
//                                 Object endtime = object.get("endTime");
//                                 if (endtime != null) {
//                                     activitiHistory.append(assignee.toString() + "/" + endtime.toString() + "->");
//                                 }else if (assignee != null && assignee != ""){
//                                     activitiHistory.append(assignee.toString() + "->");
//                                 }
//                             }
//                             if (activitiHistory.length() > 3){
//                                 activitiHistory.delete(activitiHistory.length() - 2, activitiHistory.length());
//                             }
//                             activitiHistory.append(",");
//                         }
//                     }
//                 }
//                 if (activitiHistory.length() > 2){
//                     activitiHistory.delete(activitiHistory.length()-1,activitiHistory.length());
//                 }
//             }
//             vo.setActivitiHistory(activitiHistory.toString());
//             //审核流程结束
//             //处理人员字典
//             SysUser user = sysUserMapper.getUserByName(vo.getExecutor());
//             if (user != null){
//                 vo.setExecutorText(user.getRealname());
//             }
//             //人员字典结束
//             List<EquipmentCheckTaskDetailExport> equipmentCheckTaskDetailList = equipmentCheckTaskDetailService.selectExportByMainId(main.getId());
//             vo.setEquipmentCheckTaskDetailExportList(equipmentCheckTaskDetailList);
//             pageList.add(vo);
//         }
//
//         // Step.4 自定义视图 导出pdf
//         Map<String, Object> model = new HashMap<>();
//         model.put("sheet", pageList);
//         ModelAndView mv = new ModelAndView(new PdfView());
//         mv.addObject("data",model);
//         mv.addObject("title","点检任务数据");
//         mv.addObject("user",sysUser.getRealname());
//         mv.addObject("entity",EquipmentCheckTaskExportPage.class);
//         return mv;
//     }
//
//    /**
//     * 通过excel导入数据
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile file = entity.getValue();// 获取上传文件对象
//            ImportParams params = new ImportParams();
//            params.setTitleRows(2);
//            params.setHeadRows(1);
//            params.setNeedSave(true);
//            try {
//                List<EquipmentCheckTaskPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EquipmentCheckTaskPage.class, params);
//                for (EquipmentCheckTaskPage page : list) {
//                    EquipmentCheckTask po = new EquipmentCheckTask();
//                    BeanUtils.copyProperties(page, po);
//                    equipmentCheckTaskService.saveMain(po, page.getEquipmentCheckTaskDetailList(), page.getEquipmentCheckTaskTransferList());
//                }
//                return Result.OK("文件导入成功！数据行数:" + list.size());
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
//            } finally {
//                try {
//                    file.getInputStream().close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return Result.OK("文件导入失败！");
//    }


    /**
     * 下达
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/release/{id}")
    @Operation(summary = "点检任务-下达", description = "点检任务-下达", method = "POST")
    public Result<?> release(@PathVariable(name = "id", required = true) String id) throws MBootException {
        this.equipmentCheckTaskService.release(id);
        return Result.OK("下达成功！");
    }


    /**
     * 派工
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/dispatch/{id}/{executor}")
    @Operation(summary = "点检任务-派工", description = "点检任务-派工", method = "POST")
    public Result<?> dispatch(@PathVariable(name = "id", required = true) String id, @PathVariable(name = "executor", required = true) String executor) throws MBootException {
        this.equipmentCheckTaskService.dispatch(id, executor);
        return Result.OK("派工成功！");
    }


    /**
     * 领单
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/grab/{id}")
    @Operation(summary = "点检任务-领单", description = "点检任务-领单", method = "POST")
    public Result<?> grab(@PathVariable(name = "id", required = true) String id) throws MBootException {
        this.equipmentCheckTaskService.grab(id);
        return Result.OK("领单成功！");
    }


    /**
     * 开始执行,仅记录开始作业时间
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/startExcut/{id}")
    @Operation(summary = "点检任务-开始执行", description = "点检任务-开始执行", method = "POST")
    public Result<?> startExcut(@PathVariable(name = "id", required = true) String id) throws MBootException {

        equipmentCheckTaskService.startExcut(id);
        return Result.OK("领单成功！");
    }

    @PutMapping(value = "/excut")
    @Operation(summary = "点检任务-执行", description = "点检任务-执行", method = "POST")
    public Result<?> excut(@RequestBody EquipmentCheckTaskPage equipmentCheckTaskPage, HttpServletRequest request) throws MBootException {
        equipmentCheckTaskService.excut(equipmentCheckTaskPage, request);
        return Result.OK("执行成功！");
    }


    /**
     * 转单
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/reSend/{id}/{executor}/{reason}")
    @Operation(summary = "点检任务-转单", description = "点检任务-转单", method = "POST")
    public Result<?> reSend(@PathVariable(name = "id", required = true) String id,
                            @PathVariable(name = "executor", required = true) String executor,
                            @PathVariable(name = "reason", required = true) String reason) throws MBootException {
        this.equipmentCheckTaskService.reSend(id, executor, reason);
        return Result.OK("转单成功！");
    }

}
